/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package com.huawei.rpc.common.prorocol;

import java.io.*;

/**
 * @Author Lijl
 * @ClassName JavaSerializeMessageProtocol
 * @Description java序列化信息
 * @Date 2022/2/15 13:52
 * @Version 1.0
 */
public class JavaSerializeMessageProtocol implements MessageProtocol{

    private byte[] serialize(Object obj) throws Exception{
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);) {
            oos.writeObject(obj);
            return baos.toByteArray();
        }
    }

    private Object deserialize(byte[] data)throws Exception{
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return ois.readObject();
        }
    }

    @Override
    public byte[] marshallingRequest(Request request) throws Exception {
        return this.serialize(request);
    }

    @Override
    public Request unmarshallingRequest(byte[] data) throws Exception {
        return (Request) this.deserialize(data);
    }

    @Override
    public byte[] marshallingResponse(Response response) throws Exception {
        return this.serialize(response);
    }

    @Override
    public Response unmarshallingResponse(byte[] data) throws Exception {
        return (Response) this.deserialize(data);
    }
}
